angular.module('UCX.Cmis')
.directive 'draggable', (ModelService, DnDService,CmisService)->
  (scope, element)->
    if CmisService.repository == 'fxcld'
      return
    el = element[0]
    el.draggable = true

    el.addEventListener(
      'dragstart',
      (e)->
        if scope.isEdit
          DnDService.objectIds = []
          return false
        e.dataTransfer.effectAllowed = 'move'
        #操作的文件在选中的文件中
        if scope.multipleChooseFiles.indexOf(scope.file) > -1
          objectIds = (file.id for file in scope.multipleChooseFiles)
        else
          objectIds = [scope.file.id]
        for objectId, i in objectIds
          object = ModelService.getObjectById(objectId)
          if object.allowableActions.canMoveObject
            $('tr[data-id="'+objectId+'"]').addClass('ucx-drag')
          else
            objectIds.splice(i, 1)
        DnDService.objectIds = objectIds
        if DnDService.objectIds.length == 0
          return false
        DnDService.sourceId = scope.file.getParent().id
        e.dataTransfer.setData('nothing','')
#        img = document.createElement("img")
#        if scope.file.isDocument()
#          img.src='/img/document.png'
#        else
#          img.src='/img/folder.png'
#        e.dataTransfer.setDragImage(img, 0 , 0)
      false
    )
    el.addEventListener(
      'dragend',
      (e)->
        if DnDService.objectIds
          for id in DnDService.objectIds
            $('tr[data-id="'+id+'"]').removeClass('ucx-drag')
          DnDService.clear()
#        return false
      ,
      false
    )
.directive 'droppable', (ModelService, CmisService, DnDService, $timeout)->
  {
    link: (scope, element, attrs)->
      if CmisService.repository == 'fxcld'
        return
      el = element[0]
      processDragOverOrEnter = (e) ->
#        e.dataTransfer.dropEffect = 'move'
        e.preventDefault() if (e.preventDefault)
        targetId = attrs.id
        sourceId = DnDService.sourceId
        objectIds = DnDService.objectIds
        targetFolder = ModelService.getObjectById(targetId)
        if !sourceId || sourceId == targetId || objectIds.indexOf(targetId) > -1 || !targetFolder.allowableActions.canCreateDocument
          return false
        this.classList.add('ucx-over')
        return false
      element.bind 'dragover', processDragOverOrEnter
      element.bind 'dragenter', processDragOverOrEnter
      el.addEventListener(
        'dragleave',
        (e)->
          this.classList.remove('ucx-over')
          return false
      ,
        false
      )
      el.addEventListener(
        'drop',
        (e)->
          e.preventDefault() if (e.preventDefault)
          this.classList.remove('ucx-over')

          targetId = attrs.id
          sourceId = DnDService.sourceId
          objectIds = DnDService.objectIds
          targetFolder = ModelService.getObjectById(targetId)
          if !sourceId || sourceId == targetId || objectIds.indexOf(targetId) > -1 || targetFolder.isDocument()
            return false

          sourceFolder = ModelService.getObjectById(sourceId)
          successCallback = ()->
            targetFolder.loadChildren = false
            sourceFolder.loadChildren = false
            sourceFolder.isExpand = !sourceFolder.isExpand
            # 从文件夹内往上级移动
            if(sourceFolder.path.indexOf(targetFolder.path) == 0)
              sourceFolder.children = null
              sourceFolder.folderList = []

              targetFolder.children = null
              $timeout(()->
                scope.$apply()
              ,0)
              scope.getChildren(targetFolder)
            else
              targetFolder.isExpand = !targetFolder.isExpand
              sourceFolder.children = null
              sourceFolder.folderList = []
              $timeout(()->
                scope.$apply()
              ,0)
              scope.getChildren(sourceFolder)
            for objectId in objectIds
              document = ModelService.getObjectById(objectId)
              document.createActivity('move-document', {
                document_name: document.name,
                room_name: ModelService.getRoomName(),
                room_id: ModelService.getRoomId(),
                from_folder_name: sourceFolder.name,
                to_folder_name: targetFolder.name
              })


          for objectId in objectIds
            options = {}
            options.objectId = objectId
            options.cmisaction = 'move'
            options.targetFolderId = targetId
            options.sourceFolderId = sourceId
            $.ajax(
              {
                type: 'POST'
                url:CmisService.session.defaultRepository.rootFolderUrl,
                beforeSend: (request)->
                  request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
                async: false
                data: options
                error: (data)->
                  console.log data
              }
            )
          successCallback()
      ,
        false
      )
  }
.factory "DnDService", (CmisService, $q, Utils)->
  {
    objectIds: null
    sourceId: null
    clear: ()->
      @objectIds = null
      @sourceId = null
    moveObject: (objectId, sourceId, targetid)->
      q = $q.defer()
      CmisService.session.moveObject(objectId, sourceId, targetid).ok ()->
        q.resolve('ok')
      .notOk (error)->
        if Utils.handleCmis401Error(error)
          return
        console.log error.req.url
        data = JSON.parse error.text
        q.reject(data.message)
      q.promise
  }
.directive 'undroppable', (ModelService, CmisService, DnDService, $rootScope, Utils)->
  {
    restrict:'AEC'
    link: (scope, element, attrs)->
      handler=(e)->
        e.preventDefault()
        return false
      element[0].addEventListener('drop',handler,true)
      element.bind 'dragover', handler
      element.bind 'dragenter', handler
      element.bind 'dragleave', handler
  }
